﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Globalization;

namespace LostLib.Programs
{
	/// <summary>
	/// Describes version dependancy
	/// </summary>
	partial class VersionDependancy
	{
		/// <summary>
		/// Gets all resolvers to this dependency.
		/// </summary>
		/// <returns>A sequence of resolvers.</returns>
		public IEnumerable<PackageVersion> Resolvers
		{
			get
			{
				var package = this.Package;

				if (package == null) return new PackageVersion[] { };

				switch (DependancyType)
				{
				case "newer":
					return package.PackageVersions.Where(version => version.Version >= this.Version);
				default:
					throw new NotSupportedException();
				}
			}
		}
		/// <summary>
		/// Converts Xml representation of version dependancy into VersionDependancy object.
		/// </summary>
		/// <param name="dependencyNode"></param>
		/// <returns></returns>
		public static VersionDependancy Parse(XmlNode dependencyNode)
		{
			var dependencyPackageName = dependencyNode.Attributes["package"].Value;
			var dependancyVersion =
				dependencyNode.Attributes["version"] == null
				? Dates.UnixEpoch
				: DateTime.Parse(dependencyNode.Attributes["version"].Value, CultureInfo.InvariantCulture);
			var type = dependencyNode.Attributes["type"].Value;

			var dependancy = new VersionDependancy() {
				DependancyType = type,
				PackageName = dependencyPackageName,
				Version = dependancyVersion,
			};

			return dependancy;
		}
	}
}
